package com.indexingsystem.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.indexingsystem.boss.Vo.OrderUserVo;
import com.indexingsystem.boss.Vo.PUserPwVo;
import com.indexingsystem.boss.Vo.ParentUserVo;
import com.indexingsystem.boss.Vo.PuserInfoVo;
import com.indexingsystem.boss.Vo.PusersDetailsVo;
import com.indexingsystem.boss.Vo.PusersOfterDetailVo;
import com.indexingsystem.boss.Vo.PusersSelectVo;
import com.indexingsystem.boss.Vo.StatusList;
import com.indexingsystem.boss.Vo.UserIndexVo;
import com.indexingsystem.boss.Vo.UserQueryVo;
import com.indexingsystem.boss.Vo.UserRoleVo;
import com.indexingsystem.boss.admin.mapper.PusersMapper;
import com.indexingsystem.boss.admin.mapper.RoleGroupsMapper;
import com.indexingsystem.boss.admin.mapper.RolesMapper;
import com.indexingsystem.boss.admin.mapper.UserInfosMapper;
import com.indexingsystem.boss.admin.mapper.UserInstitutionMapper;
import com.indexingsystem.boss.admin.mapper.UserRoleMapper;
import com.indexingsystem.boss.common.PagedResult;
import com.indexingsystem.boss.entity.Pusers;
import com.indexingsystem.boss.entity.RoleGroups;
import com.indexingsystem.boss.entity.Roles;
import com.indexingsystem.boss.entity.UserInfos;
import com.indexingsystem.boss.entity.UserInstitution;
import com.indexingsystem.boss.entity.UserRole;
import com.indexingsystem.boss.logback.LogCvt;
import com.indexingsystem.boss.utils.BeanUtils;
import com.indexingsystem.boss.utils.JsonUtils;
import com.indexingsystem.db.mongoDB.MongoManager;
import com.indexingsystem.db.mongoDB.impl.UserPublishMongo;
import com.indexingsystem.db.mongoDB.po.UserPublishMongoVo;
import com.indexingsystem.system.service.IPusersService;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

@Service
public class PusersServiceImpl implements IPusersService {

	private static MongoManager		manager	= new MongoManager();
	@Resource
	private PusersMapper			pusersMapper;

	@Resource
	private UserInfosMapper			userInfosMapper;

	@Resource
	private UserRoleMapper			userRoleMapper;

	@Resource
	private UserInstitutionMapper	userInstitutionMapper;

	@Resource
	private RolesMapper				rolesMapper;

	@Resource
	private RoleGroupsMapper		roleGroupsMapper;

	@Override
	public List<PusersOfterDetailVo> getUserInfoByAllUserName(String userName, String institutionsId) {
		if (StringUtils.isNotBlank( userName )) {
			List<PusersOfterDetailVo> pusersOfterDetailVoList = null;
			UserIndexVo userIndexVo = new UserIndexVo();
			userIndexVo.setUserName( userName.trim() );
			userIndexVo.setInstitutionsId( institutionsId );

			DBObject OpeObj = new BasicDBObject();
			String key = "";
			if (null != userName.trim()) {
				key = userName.trim();
			} else if (null != institutionsId.trim()) {
				key = institutionsId.trim();
			} else {
				key = userName.trim() + "+" + institutionsId.trim();
			}
			OpeObj.put( key, JsonUtils.toJson( userIndexVo ) );
			pusersOfterDetailVoList = null;// (List<PusersOfterDetailVo>)manager.findAll(
											// OpeObj,
											// MongoTableName.DH_USER_SERVICE,
											// PusersOfterDetailVo.class);
			if (null != pusersOfterDetailVoList && pusersOfterDetailVoList.size() > 0) {
				return pusersOfterDetailVoList;
			} else {
				pusersOfterDetailVoList = pusersMapper.getUserInfoByAllUserName( userIndexVo );
				OpeObj.put( key, JsonUtils.toJson( userIndexVo ) );
				// manager.add( OpeObj, MongoTableName.DH_USER_SERVICE );
				return pusersOfterDetailVoList;
			}

		} else {
			return null;
		}
	}

	@Override
	public PusersOfterDetailVo getUserByUserNameInstitution(String userName, String institutionsId) {
		UserIndexVo userIndexVo = new UserIndexVo();
		userIndexVo.setUserName( userName );
		userIndexVo.setInstitutionsId( institutionsId );

		DBObject OpeObj = new BasicDBObject();
		String key = "";
		if (null != userName.trim()) {
			key = userName.trim();
		} else if (null != institutionsId.trim()) {
			key = institutionsId.trim();
		} else {
			key = userName.trim() + "+" + institutionsId.trim();
		}

		PusersOfterDetailVo pusersOfterDetailVo = null;// manager.findOneById(
														// key,
														// MongoTableName.DH_USER_SERVICE,
														// PusersOfterDetailVo.class);
		if (null != pusersOfterDetailVo) {
			return pusersOfterDetailVo;
		} else {
			pusersOfterDetailVo = pusersMapper.getUserByUserNameInstitution( userIndexVo );
			OpeObj.put( key, JsonUtils.toJson( pusersOfterDetailVo ) );
			// manager.add( OpeObj, MongoTableName.DH_USER_SERVICE );
			return pusersOfterDetailVo;
		}

	}

	/**
	 * 通过用户名称查询用户信息.
	 * 
	 * @param userName
	 * @return
	 */
	@Override
	public PusersDetailsVo getUserInfoByUserName(String userName) {
		DBObject OpeObj = new BasicDBObject();
		String key = "";
		PusersDetailsVo pusersDetailsVo = null;
		if (null != userName) {
			key = userName;
		}
		// pusersDetailsVo=manager.findOneById( key,
		// MongoTableName.DH_USER_SERVICE, PusersDetailsVo.class);
		if (null != pusersDetailsVo) {
			return pusersDetailsVo;
		} else {
			OpeObj.put( key, JsonUtils.toJson( pusersDetailsVo ) );
			// manager.add( OpeObj, MongoTableName.DH_USER_SERVICE );
			return pusersDetailsVo;
		}

	}

	@Override
	public int deleteByPrimaryKey(String userId) {

		return pusersMapper.deleteByPrimaryKey( userId );
	}

	/**
	 * 新增用户信息.
	 */
	@Override
	public int insertSelective(Pusers record, UserInfos userInfos, UserRole userRole, UserInstitution userInstitution) throws Exception {
		Integer result = 0;

		result += pusersMapper.insertUserSelective( record );
		userInfosMapper.insertUserInfoSelective( userInfos );
		userRoleMapper.insertSelective( userRole );
		userInstitutionMapper.insertSelective( userInstitution );

		// 缓存mongo
		UserPublishMongoVo userPublishMongoVo = new UserPublishMongoVo();
		String userId = record.getUserId();
		userPublishMongoVo.setUserId( userId );
		userPublishMongoVo.setPusers( record );
		userPublishMongoVo.setUserInfos( userInfos );
		userPublishMongoVo.setUserInstitution( userInstitution );

		List<UserRole> userRolesList = new ArrayList<UserRole>();
		userRolesList.add( userRole );
		userPublishMongoVo.setUserRoleList( userRolesList );

		// 4、获取角色信息列表
		List<Roles> rolesList = new ArrayList<Roles>();

		// 5、角色组列表
		List<RoleGroups> roleGroupsList = new ArrayList<RoleGroups>();
		if (null != userRolesList && userRolesList.size() > 0) {
			for (UserRole userRoleVal : userRolesList) {
				Roles queryRoles = rolesMapper.selectByPrimaryKey( userRoleVal.getRoleId() );
				if (null != queryRoles) {
					if (!rolesList.contains( queryRoles )) {
						rolesList.add( queryRoles );
					}

					RoleGroups queryRoleGroups = roleGroupsMapper.selectByPrimaryKey( queryRoles.getRoleGroupId() );
					if (null != queryRoleGroups) {
						if (!roleGroupsList.contains( queryRoleGroups )) {
							roleGroupsList.add( queryRoleGroups );
						}
					}
				}
			}
		}

		userPublishMongoVo.setRolesList( rolesList );
		userPublishMongoVo.setRoleGroupsList( roleGroupsList );
		try {
			if (null != userPublishMongoVo) {
				UserPublishMongo.addUser( userPublishMongoVo );
			}
		} catch (Exception ex) {
			LogCvt.error( ex.getMessage(), ex );
		}
		return result;
	}

	/**
	 * 分页查询个人用户信息.
	 */
	@Override
	public PagedResult<Pusers> selectPusersList(String institutionId, Integer pageNo, Integer pageSize) {
		pageNo = pageNo == null ? 1 : pageNo;
		pageSize = pageSize == null ? 10 : pageSize;
		// startPage是告诉拦截器说我要开始分页了。分页参数是这两个。
		PageHelper.startPage( pageNo, pageSize );
		return BeanUtils.toPagedResult( pusersMapper.selectPusersList( institutionId ) );
	}

	@Override
	public PuserInfoVo selectByPrimaryKey(String userId) {
		DBObject OpeObj = new BasicDBObject();
		String key = "";
		PusersDetailsVo pusersDetailsVo = null;
		if (null != userId) {
			key = userId;
		}
		PuserInfoVo puserInfoVo = null;// manager.findOneById( key,
										// MongoTableName.DH_USER_SERVICE,
										// PuserInfoVo.class);
		if (null != puserInfoVo) {
			return puserInfoVo;
		} else {
			puserInfoVo = pusersMapper.selectByPrimaryKey( userId );
			OpeObj.put( key, JsonUtils.toJson( puserInfoVo ) );
			// manager.add( OpeObj, MongoTableName.DH_USER_SERVICE );
			return puserInfoVo;
		}
	}

	/**
	 * 启用/禁用操作.
	 * 
	 * @param record
	 * @return
	 */
	@Override
	public int updatePuserInfoByStatus(Pusers record) {

		// return pusersMapper.updateByPrimaryKeySelective( record );
		return updatePuser( record );
	}

	/**
	 * 更新用户信息.
	 * 
	 * @param pusers
	 * @return
	 */
	@Override
	public int updatePuserInfo(Pusers pusers) {
		// return pusersMapper.updateByPrimaryKeySelective( pusers );
		return updatePuser( pusers );
	}

	/**
	 * 内部修改用户信息.
	 * 
	 * @param pusers
	 * @return
	 */
	private int updatePuser(Pusers pusers) {
		Integer result = 0;
		result = pusersMapper.updateByPrimaryKeySelective( pusers );

		// 先删mongo 后加
		List<String> userIdList = new ArrayList<String>();
		userIdList.add( pusers.getUserId() );
		UserPublishMongo.deleteUserByIds( userIdList );

		UserPublishMongoVo userPublishMongoVo = getUserPublishMongoByUserId( pusers.getUserId() );
		try {
			if (null != userPublishMongoVo) {
				UserPublishMongo.addUser( userPublishMongoVo );
			}
		} catch (Exception ex) {
			LogCvt.error( ex.getMessage(), ex );
		}

		return result;
	}

	/**
	 * 通过用户id获取用户缓存信息对象.
	 * 
	 * @param userId
	 * @return
	 */
	private UserPublishMongoVo getUserPublishMongoByUserId(String userId) {
		UserPublishMongoVo userPublishMongoVo = new UserPublishMongoVo();

		// 1、获取用户信息
		Pusers pusers = pusersMapper.selectPusersInfoList( userId );
		if (null != pusers) {
			userPublishMongoVo.setUserId( pusers.getUserId() );
			userPublishMongoVo.setPusers( pusers );

			// 2、获取用户详情信息
			UserInfos userInfos = userInfosMapper.selectUserInfoByUserId( userId );
			userPublishMongoVo.setUserInfos( userInfos );

			// 3、获取用户角色列表
			List<UserRole> userRoleList = userRoleMapper.getUserRoleList( userId );
			userPublishMongoVo.setUserRoleList( userRoleList );

			// 4、获取角色信息列表
			List<Roles> rolesList = new ArrayList<Roles>();

			// 5、角色组列表
			List<RoleGroups> roleGroupsList = new ArrayList<RoleGroups>();
			if (null != userRoleList && userRoleList.size() > 0) {
				for (UserRole userRole : userRoleList) {
					Roles queryRoles = rolesMapper.selectByPrimaryKey( userRole.getRoleId() );
					if (null != queryRoles) {
						if (!rolesList.contains( queryRoles )) {
							rolesList.add( queryRoles );
						}

						RoleGroups queryRoleGroups = roleGroupsMapper.selectByPrimaryKey( queryRoles.getRoleGroupId() );
						if (null != queryRoleGroups) {
							if (!roleGroupsList.contains( queryRoleGroups )) {
								roleGroupsList.add( queryRoleGroups );
							}
						}
					}
				}
			}

			userPublishMongoVo.setRolesList( rolesList );
			userPublishMongoVo.setRoleGroupsList( roleGroupsList );

			// 获取用户机构信息
			UserInstitution queryUserInstitution = userInstitutionMapper.selectUserInstitutionByUserId( userId );
			userPublishMongoVo.setUserInstitution( queryUserInstitution );

		}

		return userPublishMongoVo;
	}

	/**
	 * 修改用户信息.
	 */
	@Override
	public int updateByPrimaryKeySelective(Pusers record, UserInfos userInfos, UserRole userRole) throws Exception {
		Integer result = 0;
		result += pusersMapper.updateByPrimaryKeySelective( record );
		userInfosMapper.updateByPrimaryKeySelective( userInfos );
		userRoleMapper.updateByPrimaryKeySelective( userRole );

		// 缓存mongo
		// 先删mongo 后加
		List<String> userIdList = new ArrayList<String>();
		userIdList.add( record.getUserId() );
		UserPublishMongo.deleteUserByIds( userIdList );
		UserPublishMongoVo userPublishMongoVo = getUserPublishMongoByUserId( record.getUserId() );
		try {
			if (null != userPublishMongoVo) {
				UserPublishMongo.addUser( userPublishMongoVo );
			}
		} catch (Exception ex) {
			LogCvt.error( ex.getMessage(), ex );
		}

		return result;
	}

	@Override
	public List<Pusers> selectPusersCountList(PusersSelectVo record) {
		return pusersMapper.selectPusersCountList( record );
	}

	/**
	 * 分页查询显示个人信息.
	 */
	@Override
	public PagedResult<Pusers> queryListByPage(PusersSelectVo puserVo) {
		DBObject OpeObj = new BasicDBObject();
		PagedResult<Pusers> pagedResultPusersList = null;
		pagedResultPusersList = null;// (PagedResult<Pusers>) manager.findAll(
										// puserVo,
										// MongoTableName.DH_USER_SERVICE,
										// PagedResult.class );
		if (null != pagedResultPusersList) {
			return pagedResultPusersList;
		} else {
			Integer pageNo = puserVo.getPageNumber() == null ? 1 : puserVo.getPageNumber();
			Integer pageSize = puserVo.getPageSize() == null ? 10 : puserVo.getPageSize();
			// startPage是告诉拦截器说我要开始分页了。分页参数是这两个。
			PageHelper.startPage( pageNo, pageSize );
			pagedResultPusersList = BeanUtils.toPagedResult( pusersMapper.selectPusersCountList( puserVo ) );
			OpeObj.put( JsonUtils.toJson( puserVo ), JsonUtils.toJson( pagedResultPusersList ) );
			// manager.add( OpeObj, MongoTableName.DH_USER_SERVICE );
			return pagedResultPusersList;
		}
	}

	/**
	 * 角色添加用户时，未添加角色用户关系的用户列表.
	 * 
	 * @param userName
	 * @return
	 */
	@Override
	public PagedResult<UserRoleVo> selectNoAddUserInfoList(UserQueryVo userQueryVo) {
		DBObject OpeObj = new BasicDBObject();
		PagedResult<UserRoleVo> pagedResultUserRoleVoList = null;// (PagedResult<UserRoleVo>)
																	// manager.findAll(
																	// userQueryVo,
																	// MongoTableName.DH_USER_SERVICE,
																	// PagedResult.class
																	// );
		if (null != pagedResultUserRoleVoList) {

		} else {

		}
		Integer pageNo = userQueryVo.getPageNumber() == null ? 1 : userQueryVo.getPageNumber();
		Integer pageSize = userQueryVo.getPageSize() == null ? 10 : userQueryVo.getPageSize();
		// startPage是告诉拦截器说我要开始分页了。分页参数是这两个。
		PageHelper.startPage( pageNo, pageSize );
		return BeanUtils.toPagedResult( pusersMapper.selectNoAddUserInfoList( userQueryVo ) );
	}

	/**
	 * 获取个人用户总数.
	 * 
	 * @return
	 */
	@Override
	public Integer getNoAddUserInfoListCount(UserQueryVo userQueryVo) {
		return pusersMapper.getNoAddUserInfoListCount( userQueryVo );
	}

	/**
	 * 获取个人用户总数.
	 */
	@Override
	public Integer getPusersCount(String institutionId) {
		return pusersMapper.getPusersCount( institutionId );
	}

	/**
	 * 通过机构id获取机构用户列表.
	 * 
	 * @param institutionId
	 * @return
	 */
	@Override
	public List<Pusers> getInstitutionsPUserListById(String institutionId) {
		return pusersMapper.getInstitutionsPUserListById( institutionId );
	}

	@Override
	public List<Pusers> selectNotBindUser() {
		return pusersMapper.selectNotBindUser();
	}

	/**
	 * 通过用户id查询用户当前密码.
	 * 
	 * @param userId
	 * @return
	 */
	@Override
	public PUserPwVo getPasswordByUserId(String userId) {
		return pusersMapper.getPasswordByUserId( userId );
	}

	/**
	 * 用户登录.
	 * 
	 * @param userName
	 * @param password
	 * @return
	 */
	@Override
	@RequiresRoles("admin")
	public Pusers login(String userName) {
		// String currLoginPw = MD5Util.getMD5Str(MD5Util.getMD5Str(password) +
		// userName);
		Pusers pusers = pusersMapper.login( userName );
		return pusers;
	}

	/**
	 * 通过用户id校验所属机构是否禁用.
	 * 
	 * @param userId
	 * @return
	 */
	@Override
	public String getUseridByInstitutionsStatus(String userId) {
		return pusersMapper.getUseridByInstitutionsStatus( userId );
	}

	/**
	 * 批量删除用户信息.
	 * 
	 * @param userIdList
	 * @return
	 */
	@Override
	public int deleteUserInfoByIdBatch(List<String> userIdList) throws Exception {
		int result = 0;
		if (null != userIdList && userIdList.size() > 0) {
			result = pusersMapper.deletePusersByIdBatch( userIdList );
			userInfosMapper.deleteByUserInfosByIdBatch( userIdList );
			userRoleMapper.deleteUserRoleInfoByUserId( userIdList );
			userInstitutionMapper.deleteBatchUserInstitution( userIdList );

			// 删除mongo 缓存
			UserPublishMongo.deleteUserByIds( userIdList );
		}
		return result;
	}

	/**
	 * 通过条件查询获取用户符号条件的总数量.
	 * 
	 * @param record
	 * @return
	 */
	@Override
	public Integer getPuserQueryList(PusersSelectVo record) {
		return pusersMapper.getPuserQueryList( record );
	}

	/**
	 * 批量启用，禁用功能.
	 * 
	 * @param statusList
	 * @return
	 */
	@Override
	public int batchUpdateUserInfoWithList(List<StatusList> list) {
		Integer result = 0;
		if (null != list && list.size() > 0) {
			result += pusersMapper.batchUpdateUserInfoWithList( list );

			// 缓存mongo
			// 先删mongo 后加
			for (StatusList statusInfo : list) {
				List<String> userIdList = new ArrayList<String>();
				userIdList.add( statusInfo.getId() );
				UserPublishMongo.deleteUserByIds( userIdList );
				UserPublishMongoVo userPublishMongoVo = getUserPublishMongoByUserId( statusInfo.getId() );
				try {
					if (null != userPublishMongoVo) {
						UserPublishMongo.addUser( userPublishMongoVo );
					}
				} catch (Exception ex) {
					LogCvt.error( ex.getMessage(), ex );
				}
			}
		}
		return result;
	}

	/**
	 * 通过机构id查询机构管理员所属用户信息列表.
	 * 
	 * @param institutionsId
	 * @return
	 */
	@Override
	public List<ParentUserVo> getUserListByInstitutionsId(String institutionsId) {
		return pusersMapper.getUserListByInstitutionsId( institutionsId );
	}

	@Override
	public String getUserId(String userId) {
		return pusersMapper.getUserId( userId );
	}

	/**
	 * 通过用户id和机构id查询机构所属用户是否存在.
	 * 
	 * @param orderUserVo
	 * @return
	 */
	@Override
	public Integer getOrderUserInfoCount(OrderUserVo orderUserVo) {
		return pusersMapper.getOrderUserInfoCount( orderUserVo );
	}

	@Override
	public Pusers selectPusersInfoList(String userId) {
		return pusersMapper.selectPusersInfoList( userId );
	}

	@Override
	public Integer getPuserStatusCount(String institutionId) {
		return pusersMapper.getPuserStatusCount( institutionId );
	}

	@Override
	public List<ParentUserVo> selectUserBy() {
		return pusersMapper.selectUserBy();
	}

	@Override
	public List<ParentUserVo> selectUserListByUserName(String userName) {
		return pusersMapper.selectUserListByUserName( userName );
	}

	@Override
	public Object mongoCache(Object object, int type) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Integer selectUserCount() {
		return pusersMapper.selectUserCount();
	}

	@Override
	public Integer selectCharUserCount(List<String> institutionId) {
		return pusersMapper.selectCharUserCount( institutionId );
	}

	@Override
	public Pusers getDhUsersByName(String username) {
		// TODO Auto-generated method stub
		return pusersMapper.getDhUsersByName( username );
	}
}